// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-08-20

package gen_annotation

import (
	_ "embed"
	"fmt"
)

//go:embed template_controller.tpl
var templateController string

// SeekerController
// is a component for controller files manager.
type SeekerController struct {
	Seeker *Seeker

	result *ResultController
	target string
}

// Add
// adds a controller file resource to manager.
func (o *SeekerController) Add(resource *Resource) (err error) {
	return resource.Reader(o.Seeker.Provider, o)
}

// Do
// generate and save to target file.
func (o *SeekerController) Do() (err error) {
	err = o.Seeker.Save(o.result.Ready(), o.target, templateController)
	return
}

// Match
// matches the line text of a resource file.
func (o *SeekerController) Match(resource *Resource, comment *Comment, line int, text string) (err error) {
	var (
		entity *EntityController
		match  []string
	)

	// Match
	// crontab name rule.
	if m := ResourceRegexMatchController.FindStringSubmatch(text); len(m) > 0 {
		// Group type definition.
		match = m
	} else if n := ResourceRegexMatchController2.FindStringSubmatch(text); len(n) > 0 {
		// Single type definition.
		match = n
	}

	// Return
	// if not match on controller.
	if match == nil || len(match) == 0 || !ResourceRegexMatchControllerName.MatchString(match[1]) {
		return
	}

	// Creates
	// a new entity.
	entity = NewEntityController(match[1])
	entity.Import = resource.Import
	entity.Package = resource.Package
	entity.File = fmt.Sprintf(`%s/%s`, resource.Path, resource.Src)
	entity.Line = line

	if resource.Folder != "" {
		entity.Prefix = fmt.Sprintf(`/%s`, resource.Folder)
	}

	// Range annotations.
	for anno, list := range comment.GetAnnotations() {
		switch anno {
		case AnnotationRoutePrefix:
			for _, item := range list {
				if s := item.First(); s != "" {
					entity.Prefix = s
					break
				}
			}
		case AnnotationMiddleware:
			for _, item := range list {
				for _, s := range item.Values() {
					if s != "" {
						entity.Middlewares = append(entity.Middlewares, s)
					}
				}
			}
		}
	}

	// Parse succeed.
	o.result.AddEntity(entity)
	o.Seeker.Container.GetOutput().Info(`  - found: source="%s/%s:%d", struct="%s"`, resource.Path, resource.Src, line, entity.Struct)
	return
}

// Target
// returns a file path for generated content.
func (o *SeekerController) Target() string { return o.target }

// +---------------------------------------------------------------------------+
// | Access methods                                                            |
// +---------------------------------------------------------------------------+

func (o *SeekerController) init() *SeekerController {
	o.result = NewResultController(o.Seeker.Command, o.Seeker.Provider.AnnotationPkg)
	o.target = fmt.Sprintf(`%s/%s/annotation_controllers.go`, o.Seeker.Provider.WorkingDir, o.Seeker.Provider.AnnotationPath)
	o.Seeker.Container.GetOutput().Info(`+ [scanner:controller]`)
	return o
}
